package com.example.addressbook.views;

import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.progress.UIJob;

import com.example.addressbook.entities.Address;
import com.example.addressbook.services.AddressBookServices;
import com.example.addressbook.services.IAddressService;
import com.example.addressbook.table.MyCellLabelProvider;
import org.eclipse.swt.layout.RowData;

import swing2swt.layout.FlowLayout;
import org.eclipse.swt.layout.FillLayout;

public class AddressList extends ViewPart {
	private Table table;
	private TableViewer tableViewer;
	private IAddressService service;
	
	public AddressList() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void createPartControl(Composite parent) {
		parent.setLayout(new FillLayout(SWT.HORIZONTAL));
		
		tableViewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION);
		table = tableViewer.getTable();
		tableViewer.setContentProvider( ArrayContentProvider.getInstance());
		
		TableViewerColumn viewerNameColumn = new TableViewerColumn(tableViewer, SWT.NONE);
		viewerNameColumn.getColumn().setText("Names");
		viewerNameColumn.getColumn().setWidth(100);
		viewerNameColumn.setLabelProvider( new MyCellLabelProvider());
		
		
		refresh();
		// TODO Auto-generated method stub
		
		getSite().setSelectionProvider( tableViewer);
	}

	public void refresh() {
		Job job = new Job("Load Addresses") {
			
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				if (service == null)
					service = AddressBookServices.getAddressService();
				List<Address> allAddresses = service.getAllAddresses();
				setAddressList(allAddresses);
				return Status.OK_STATUS;
			}
		};
		job.schedule();
	}
	
	private void setAddressList(final List<Address> allAddresses) {
		UIJob uijob = new UIJob("Display Addresses") {
			
			@Override
			public IStatus runInUIThread(IProgressMonitor monitor) {
				tableViewer.setInput( allAddresses);
				return Status.OK_STATUS;
			}
		};
		uijob.schedule();
	}
	
	@Override
	public void setFocus() {
		table.setFocus();
	}

}
